/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.odg.m_ui.util;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Frame;
import java.io.File;
import java.util.Enumeration;
import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author yura
 */
public class UIUtil {

    public static File openFileChooser(int chooserType, String title) {
        JFileChooser fch = new JFileChooser();
        fch.setDialogType(chooserType);
        fch.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fch.setDialogTitle(title);
        int returnVal = fch.showOpenDialog(null);

        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return null;
        }

        return fch.getSelectedFile();
    }

    public static void openInFileBrowser(File file, String errorTitle) {
        try {
            Desktop.getDesktop().open(file.getParentFile());
        } catch (Exception ex) {
        }
        try {
            Desktop.getDesktop().open(file);
        } catch (Exception ex) {
            try {
                Desktop.getDesktop().edit(file);
            } catch (Exception ex2) {
                UIUtil.niceEx(ex, errorTitle, "Can't open: " + file + "\n");
            }
        }
    }

    /**
     * If expand is true, expands all nodes in the tree.
     * Otherwise, collapses all nodes in the tree.
     */
    public static void expandAll(JTree tree, boolean expand) {
        TreeNode root = (TreeNode) tree.getModel().getRoot();

        // Traverse tree from root
        expandAll(tree, new TreePath(root), expand);
    }

    private static void expandAll(JTree tree, TreePath parent, boolean expand) {
        // Traverse children
        TreeNode node = (TreeNode) parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                expandAll(tree, path, expand);
            }
        }

        // Expansion or collapse must be done bottom-up
        if (expand) {
            tree.expandPath(parent);
        } else {
            tree.collapsePath(parent);
        }
    }

    public static void niceEx(Throwable ex, String title, String additionalTxt){
        String step = "";
        int i = 0;
        StringBuilder sb = new StringBuilder().append(additionalTxt);
        for (char ch : String.valueOf(ex).toCharArray()) {
            if (ch == ';'){
                sb.append(";\n").append(step);
                i = 0;
            } else if (ch == ':'){
                step += "   ";
                sb.append(":\n").append(step);
                i = 0;
            } else if ((Character.isWhitespace(ch) || ch == '.') && i >= 80){
                sb.append("\n     ").append(step).append(ch);
                i = 0;
            } else {
                sb.append(ch);
            }
            i ++;
        }

        JTextPane ta = new JTextPane();
        ta.setText(sb.toString());
        ta.setBackground(Color.WHITE);
        ta.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
        ta.setSize(400, 300);
        ta.setEditable(false);
        JOptionPane.showMessageDialog(null, new JScrollPane(ta), title,
                JOptionPane.ERROR_MESSAGE);
    }
    
    public static class ProgressDialog extends JDialog {
        private JProgressBar progressBar;
        
        public ProgressDialog(Frame owner, String title, String note, boolean indeterminate) {
            super(owner, title, true);
            progressBar = new JProgressBar();
            progressBar.setIndeterminate(indeterminate);
            
            JPanel contents = (JPanel)getContentPane(); 
            contents.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); 
            contents.add(new JLabel(note), BorderLayout.NORTH); 
            contents.add(progressBar); 

            setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); 
            
            pack();
            setLocationRelativeTo(null);
        }

        public JProgressBar getProgressBar() {
            return progressBar;
        }
        
    }
}
